package es.prodevelop.arport.tasks;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;

import android.app.Activity;
import android.os.AsyncTask;
import android.widget.Toast;
import es.prodevelop.arport.ARShipsActivity;

public class GetShipsInfoTask extends AsyncTask<Void, Integer, Boolean> {

	private static final String HIGH_SCORES_URI = "http://soletaken.disca.upv.es:8080/CMU/rest/highscores";

	private static final int SERVICE_NOT_AVAILABLE = 0;

	private Activity activity = null;

	public GetShipsInfoTask(Activity activity) {
		this.activity = activity;
	}

	@Override
	protected void onPreExecute() {
		// nothing to do
	}

	@Override
	protected Boolean doInBackground(Void... params) {
		BasicHttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
		HttpConnectionParams.setSoTimeout(httpParams, 5000);

		HttpClient client = new DefaultHttpClient(httpParams);
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("name", ""));

		HttpGet request = new HttpGet(HIGH_SCORES_URI + "?"
				+ URLEncodedUtils.format(pairs, "utf-8"));

		// try {
		// HttpResponse response = client.execute(request);
		// HttpEntity entity = response.getEntity();
		//
		// if (entity != null) {
		// InputStream stream = entity.getContent();
		// BufferedReader reader = new BufferedReader(
		// new InputStreamReader(stream));
		// StringBuilder sb = new StringBuilder();
		// String line = null;
		// while ((line = reader.readLine()) != null) {
		// sb.append(line + "\n");
		// }
		// stream.close();
		//
		// String responseString = sb.toString();
		// GsonBuilder builder = new GsonBuilder();
		// Gson gson = builder.create();
		// JSONObject json = new JSONObject(responseString);
		// // HighScoreList list = gson.fromJson(json.toString(),
		// // HighScoreList.class);
		// // ((Scores) activity).setMapScores(list);
		// }

		String jsonData = "[{\"id\":\"1\",\"type\":2,\"altitude\":0,\"longitude\":-0.3320,\"latitude\":39.460146,\"name\":\"Buque 1\",\"description\":\"Buque de guerra de la marina...\"}]";
		((ARShipsActivity) activity).refreshARShips(jsonData);

		// } catch (IOException e) {
		// publishProgress(SERVICE_NOT_AVAILABLE);
		// } catch (JSONException e) {
		// e.printStackTrace();
		// }

		return true;
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		for (int v : values) {
			if (v == SERVICE_NOT_AVAILABLE) {
				Toast.makeText(activity.getApplicationContext(),
						"NO DISPONIBLE", Toast.LENGTH_SHORT).show();
			}
		}
	}

}
